package com.easy.user.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easy.common.bean.User;
import com.easy.common.service.IUserService;
import com.easy.common.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;
    @GetMapping("/{id}")
    public Result getUserById(@PathVariable Integer id) {
        return Result.success(userService.getUserById(id));
    }
    @PostMapping("/list")
    public Result getAll(@RequestBody User user) {
        return Result.success(userService.getAll(user));
    }

    @PostMapping
    public Result addUser(@RequestBody User user) {
        int result = userService.addUser(user);
        return result > 0 ? Result.success("添加成功", null) : Result.fail(500, "添加失败");
    }

    @PutMapping
    public Result updateUser(@RequestBody User user) {
        int result = userService.updateUser(user);
        return result > 0 ? Result.success("更新成功", null) : Result.fail(500, "更新失败");
    }

    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        int result = userService.deleteUser(id);
        return result > 0 ? Result.success("删除成功", null) : Result.fail(500, "删除失败");
    }

    @PostMapping("/page")
    public Result getPage(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize, 
                               @RequestBody(required = false) User user) {
        IPage<User> page = new Page<>(pageNum, pageSize);
        if (user == null) {
            user = new User();
        }
        return Result.success(userService.getPage(user, page));
    }

    @RequestMapping("/getuser")
    public String getUser() {
        return "hello world";
    }
}
